package de.koller.planet2D.frame.previewRender;

import de.koller.planet2D.frame.IPositionClickNotifier;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JPanel;

public class RenderPanel extends JPanel {

	private final PRenderRoot node;
	public final Set<IPositionClickNotifier> clickNotifier = new HashSet<>();
	public final Set<IPositionClickNotifier> moveNotifiers = new HashSet<>();
	
	public RenderPanel( PRenderRoot node ) {
		this.node = node;
		
		this.setBackground( Color.BLACK );
		this.setPreferredSize( new Dimension( 800, 600 ) );
		
		MouseHandler mh = new MouseHandler();
		this.addMouseListener( mh );
		this.addMouseMotionListener( mh );
		
		CameraSteerListener csl = new CameraSteerListener( node.camera );
		this.addMouseListener( csl );
		this.addMouseMotionListener( csl );
		this.addMouseWheelListener( csl );
	}

	@Override
	protected void paintComponent( Graphics g ) {
		super.paintComponent( g );
		
		node.renderPreview( (Graphics2D)g );
		node.proot.updateThis();
	}
	
	
	private class MouseHandler extends MouseAdapter {

		@Override
		public void mousePressed( MouseEvent e ) {
			if( e.getButton() != 1 )
				return;
			
			double v[] = getMousePos( e );
			for( IPositionClickNotifier i : clickNotifier )
				i.notifyPosition( v[0], v[1] );
		}

		@Override
		public void mouseMoved( MouseEvent e ) {
			double v[] = getMousePos( e );
			for( IPositionClickNotifier i : moveNotifiers )
				i.notifyPosition( v[0], v[1] );
		}
		
		private double[] getMousePos( MouseEvent e ) {
			double x = 0;
			double y = 0;
			
			try {
				Point2D tr = node.camera.getUsedTransform().inverseTransform( e.getPoint(), null );
				x = tr.getX();
				y = tr.getY();
			} catch ( NoninvertibleTransformException ex ) {
				assert true;
			}
			
			return new double[] { x, y };
		}
	}
	
}
